#include "pcap_device_retriever.h"

#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif

#define HAVE_REMOTE

#include "pcap.h"

pcap_device_info::pcap_device_info()
	: m_str_device_name(0)
	, m_str_device_description(0)
{
	;
}

pcap_device_info::~pcap_device_info()
{
	delete[]m_str_device_name;
	delete[]m_str_device_description;
}

void pcap_device_info::set_pcap_device_name(char * device_name)
{
	cpy_string(&m_str_device_name, device_name);
}

void pcap_device_info::set_pcap_device_description(char * device_description)
{
	cpy_string(&m_str_device_description, device_description);
}

char * pcap_device_info::get_pcap_device_name()
{
	return m_str_device_name;
}

char * pcap_device_info::get_pcap_device_description()
{
	return m_str_device_description;
}

void pcap_device_info::cpy_string(char ** ptr_str_dest, char * str_src)
{
	delete[] * ptr_str_dest;

	int len = strlen(str_src);

	*ptr_str_dest = new char[len + 1];
	memset(*ptr_str_dest, 0, len + 1);

	strcpy_s(*ptr_str_dest, len + 1 , str_src);
}

pcap_device_retriever::pcap_device_retriever()
{
	;
}

pcap_device_retriever::~pcap_device_retriever()
{
	;
}

bool pcap_device_retriever::get_device_list(std::vector< pcap_device_info* >& info)
{
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int i = 0;
	char errbuf[PCAP_ERRBUF_SIZE];

	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		return false;
	}

	for (d = alldevs; d != NULL; d = d->next)
	{
		pcap_device_info * ptr_info = new pcap_device_info;
		ptr_info->set_pcap_device_name(d->name);
		ptr_info->set_pcap_device_description(d->description);

		i++;

		info.push_back(ptr_info);
	}

	if (i == 0)
	{
		return false;
	}

	pcap_freealldevs(alldevs);

	return true;
}
